<template>
  <section>
    <!--工具条-->
    <!--    高级查询—+新增-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true">
        <el-form-item>
          <el-input v-model="keyword" placeholder="请输入关键字"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-on:click="keywordQuery" icon="el-icon-search">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd" icon="el-icon-circle-plus-outline">新增</el-button>
        </el-form-item>
      </el-form>
    </el-col>
    <!--
    :data=petTypes 列表数据
    highlight-current-row v-loading="listLoading" 当前行高亮
    v-loading加载框
    -->
    <!--列表-->
    <el-table :data="petTypes" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" width="60">
      </el-table-column>
      <!--      <el-table-column prop="sn" label="部门编号" width="150" sortable>-->
      <!--      </el-table-column>-->
      <el-table-column prop="name" label="名称" width="100" sortable>
      </el-table-column>
      <el-table-column prop="description" label="描述" width="100"  sortable>
      </el-table-column>
      <el-table-column prop="parent.name" label="类型" width="100"  sortable>
      </el-table-column>
      <el-table-column label="操作" width="220">
        <template scope="scope">
          <el-button size="medium" type="primary" round icon="el-icon-edit" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" size="medium" round icon="el-icon-delete " @click="handleDel(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--工具条  批量删除+分页栏-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <el-pagination layout="sizes,prev, pager, next,jumper,total" @current-change="handleCurrentChange"
                     @size-change="handleSizeChange" :page-size="pageSize" :total="totals"
                     :current-page="currentPage" :page-sizes="sizes" style="float:right;">
      </el-pagination>
    </el-col>

    <!--编辑界面-->
    <!-- 添加或修改的对话框
    el-dialog - elementUi提供的对话框 = 模态框
    	:title="title" - 动态改变标题
    	:visible.sync="saveFormVisible"  - 模态框的显示状态
    	:close-on-click-modal="false" - 关闭模态框只能通过模态框的x关闭，点击空白处不能关闭模态框
    el-form - 表单
    	:model="saveForm" - 绑定表单对象
    	label-width="80px" - 标签宽度
    	:rules="saveFormRules" - 验证规则
    	ref="saveForm" - 为当前模态框取名
    	prop="name" - 如果当前字段要验证，就必须写，出现*
    	auto-complete="off" - 不自动提示
-->
    <el-dialog :title=title :visible.sync="saveFormVisible" :close-on-click-modal="false">
      <el-form :model="saveForm" label-width="100px" :rules="saveFormRules" ref="saveForm">
        <el-form-item label="宠物名称" prop="name">
          <el-input v-model="saveForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="成本价">
          <el-input v-model="saveForm.costprice" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="市场价">
          <el-input v-model="saveForm.saleprice" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="宠物类型">
          <el-cascader v-model="saveForm.typeId"
                       :options="petTypeTree"
                       :props="{ checkStrictly: true,label:'name',value:'id' }"
                       clearable></el-cascader>
        </el-form-item>
        <el-form-item label="宠物图片">
          <el-input v-model="saveForm.resources" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="宠物状态">
          <el-radio-group v-model="saveForm.state">
            <el-radio class="radio" :label="1">上架</el-radio>
            <el-radio class="radio" :label="0">下架</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="所属店铺">
          <el-select v-model="saveForm.shopId" clearable placeholder="请选择">
            <el-option v-for="item in shops"
                       :label="item.name"
                       :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="saveFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="saveSubmit" :loading="saveLoading">提交</el-button>
      </div>
    </el-dialog>

    <!--新增界面-->
  </section>
</template>

<script>
// import util from '../../common/js/util'
// import { getPetTypeListPage, removePetType, batchRemovePetType, savePetType, addPetType } from '../../api/api';

export default {
  data() {
    return {
      //分页查询的相关参数
      petTypes: [],//列表数据
      pageSize:5,//每页显示的条数
      currentPage:1,//当前页数
      totals:0,//总数量
      sizes:[5,10,15,20],
      title:"",
      // isId:true,
      listLoading: false,//加载框 默认不显示

      shops:[],
      //部门级联数
      petTypeTree:[],
      //2.高级查询的相关数据
      //2.高级查询的相关数据
      keyword:'',

      //3.批量删除
      sels: [],//列表选中列
      // total: 0,
      //4.添加或者修改相关的数据
      saveFormVisible: false,//控制对话框是否显示
      saveLoading: false,//保存的加载框 默认不显示
      saveFormRules: {//表单项验证
        sn: [
          { required: true, message: '请输入编号', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入名称', trigger: 'blur' }
        ]
      },
      //添加或者修改中对话框的值
      saveForm: {
        id: null,
        name: '',
        costprice: 0,
        saleprice: 0,
        typeId: null,
        resources: '',
        state: 0, //默认下架 - 前台看不见这个宠物 - 审核之后才能上架
        shopId: null
      }
    }
  },
  methods: {
    //点击当前页进行页面跳转
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getPetTypes();
    },
    handleSizeChange(val){
      this.pageSize=val;
      this.getPetTypes();
    },
    //2.防止查询的时候不在第一页的时候，通过关键字查询的时候 出现没有数据的情况
    keywordQuery(){
      this.currentPage=1;
      this.getPetTypes();
    },
    //1.获取部门列表-新
    getPetTypes() {
      let para={
        currentPage:this.currentPage,
        pageSize:this.pageSize,
        //前一个是要传递给后端的值 后面是当前页面的值
        keyword:this.keyword,
      };
      this.listLoading = true;//显示加载框
      this.$http.post("/petType",para).then(res=>{
        this.petTypes = res.data.data;//给数组赋值
        this.totals = res.data.totals;//传递总数量-计算分页栏
        this.listLoading = false;//关闭加载框
      }).catch(res=>{
        this.$message.error("系统繁忙,请稍后访问");
      })

    },
    //3.删除功能实现 并且实现如果在最后一页进行删除 数据删除完成之后跳转到上一个页面
    handleDel: function (index, row) {
      this.$confirm('确认删除该记录吗?', '提示', {
        type: 'warning'
      }).then(() => {
        //显示加载框
        this.listLoading = true;
        this.$http.delete("/petType/" + row.id).then(res => {
          this.listLoading = false;

          if (res.data.success) {
            this.$message.success("删除成功");
            if(((this.currentPage*this.pageSize)-this.totals)>=this.pageSize-1){
              this.currentPage=this.currentPage-1;
            }
            this.getPetTypes();
          } else {
            this.$message.error("系统繁忙，请稍后再试[500]");
          }
        }).catch(res => {
          this.$message.error("删除失败，请稍后再试【404】")
        })
      }).catch(()=>{

      })
    },

    //显示编辑界面
    //7.点击修改按钮展示对话框
    handleEdit: function (index, row) {
      this.title="修改";
      //弹出对话框
      this.saveFormVisible = true;
      //回显数据：创建一个新的空对象{}，然后将row中的数据拷贝给{}
      this.saveForm = Object.assign({}, row);
      this.getShop();
      this.getPetTree();
    },
    //8.点击新增按钮弹出对话框
    handleAdd: function () {
      this.title="新增";
      this.saveFormVisible = true;
      this.saveForm = {
        id: null,
        name: '',
        costprice: 0,
        saleprice: 0,
        typeId: null,
        resources: '',
        state: 0, //默认下架 - 前台看不见这个宠物 - 审核之后才能上架
        shopId: null
      };
      this.getShop();
      this.getPetTree();
    },
    //添加或者编辑
    saveSubmit: function () {
      this.$refs.saveForm.validate((valid) => {
        //valid是验证表单项是否成功
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            //显示加载框
            this.saveLoading=true;
            let para = Object.assign({}, this.saveForm);
            //1.不修改上级部门，没有点级联框：2
            //2.不修改上级部门，点了级联框选择过其它部门：[2]
            //3.去掉上级部门：[]
            //4.[3,9,12]
            //5.null

            // console.log(para.parent_id);
            var isArr = para.parent_id
            if(Array.isArray(isArr)){
              //如果是空数组
              if(isArr.length==0){
                para.parent_id = null;
              }else{//如果不是空数组
                para.parent_id=isArr[isArr.length-1];
              }
            }

            this.$http.put("/petType",para).then(res=>{
              this.saveLoading=false;
              this.saveFormVisible=false;
              if(res.data.success){
                this.getPetTypes();
                this.$message.success(this.title+"成功");
              }else{
                this.$message.error("系统繁忙，请稍后再试【500】");
              }
            }).catch(res=>{
              this.$message.error("系统繁忙，请稍后再试【400,404】");
            })
          });
        }
      });
    },

    //批量删除 将当前行的数据赋值给sels
    selsChange: function (sels) {
      this.sels = sels;
    },
    //4.批量删除
    batchRemove: function () {
      //记住传递参数回去的时候要避免转成字符串
      var ids = this.sels.map(item => item.id);
      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        //加载列表
        this.listLoading = true;
        //也可以用/petType/+ids方式
        this.$http.patch("/petType",ids).then(res=>{
          //  关闭加载框
          this.listLoading = false;
          if(res.data.success){
            this.$message.success("批量删除成功");
            //批量删除之后要到第一页
            this.currentPage=1;
            this.getPetTypes();
          }else{
            this.$message.error("系统繁忙，请稍后再试[500]");
          }
        }).catch(res=>{
          this.$message.error("系统繁忙，请稍后再试[404]");
        })
        //NProgress.start();
        // let para = { ids: ids };
        // batchRemovePetType(para).then((res) => {
        // 	this.listLoading = false;
        // 	//NProgress.done();
        // 	this.$message({
        // 		message: '删除成功',
        // 		type: 'success'
        // 	});
        // 	this.getPetTypes();
        // });
      }).catch(() => {

      });
    },
    getShop(){
      this.$http.get("/shop").then(res=>{
        this.shops = res.data;
      }).catch(res=>{

      })
    },
    getPetTree(){
      this.$http.get("/petType/petTree").then(res=>{
        this.petTypeTree=res.data;
      }).catch(res=>{

      })
    }
  },
  //页面加载列表
  mounted() {
    this.getPetTypes();
  }
}

</script>

<style scoped>

</style>